extends CharacterBody2D
class_name Player

const SPEED = 180.0
const JUMP_VELOCITY = -300.0
signal died
@export var dead_speed = 520
# Get the gravity from the project settings to be synced with RigidBody nodes.
var gravity = ProjectSettings.get_setting("physics/2d/default_gravity")

@onready var animated_sprite_2d = $AnimatedSprite2D

var is_dead: bool = false
func _physics_process(delta):
	if (is_dead):
		return
	# Add the gravity.
	if not is_on_floor():
		velocity.y += gravity * delta
	if (is_on_floor() and Input.is_action_pressed("jump")):
		velocity.y += JUMP_VELOCITY
	# 获取输入方向
	var direction = Input.get_axis("move_left", "move_right")
	
	if direction > 0:
		animated_sprite_2d.flip_h = false
	elif direction < 0:
		animated_sprite_2d.flip_h = true

	
	# 播放控制动画
	if is_on_floor():
		if direction == 0:
			animated_sprite_2d.play("idle")
		else:
			animated_sprite_2d.play("run")
	else:
		animated_sprite_2d.play("jump")
	
	if direction:
		velocity.x = direction * SPEED
	else:
		velocity.x = move_toward(velocity.x, 0, SPEED)
	
	move_and_slide()

func dead() -> void:
	$AnimationPlayer.play("dead")
	is_dead = true
	died.emit()
